package com.bbcare.nutritious.plat.service.imp;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.bbcare.comm.AppException;
import com.bbcare.comm.Constants;
import com.bbcare.comm.DateTimeUtil;
import com.bbcare.comm.DateUtil;
import com.bbcare.comm.ErrorCode;
import com.bbcare.comm.SeqUtil;
import com.bbcare.nutritious.plat.entity.PtActivitiesDaily;
import com.bbcare.nutritious.plat.entity.PtGymnasticBarbell;
import com.bbcare.nutritious.plat.service.IGymnasticBarbellService;
import com.bbcare.nutritious.plat.store.ibatis.IActivityHuamiDao;
import com.bbcare.nutritious.plat.store.ibatis.IGymnasticBarbellDao;
import com.bbcare.nutritious.plat.store.ibatis.IWeightDao;

/**
 * 体操杠铃和上下班信息接口实现
 */
@Service
public class GymnasticBarbellService implements IGymnasticBarbellService {

	public static final Logger logger = Logger.getLogger(GymnasticBarbellService.class);

    @Autowired
    private IGymnasticBarbellDao gymnasticBarbellDao;
    @Autowired
    private IWeightDao weightDao;
    @Autowired
    private IActivityHuamiDao activityHuamiDao;
    
   /**
    * 保存或修改孕妇体重数据
    */
    @Override
	public Map<String, Object> saveGymnasticBarbell(PtGymnasticBarbell gymnasticBarbell) throws Exception {
    	//创建线程安全的hashmap返回对象
    	Map<String,Object> rspMap = Collections.synchronizedMap(new HashMap<String,Object>());
    	//判断该用户是否存在某租户下
    	String tenantId = weightDao.getUserTenantIdByUserId(gymnasticBarbell.getUserId());
    	if(StringUtils.isEmpty(tenantId)){
    		throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST,"患者信息不存在");
    	}
    	gymnasticBarbell.setTenantId(tenantId);
    	gymnasticBarbell.setTestDate(DateTimeUtil.getNowDateStr(DateTimeUtil.yyyy_MM_dd));
    	String nowTime = DateUtil.getTimeString(DateUtil.getSysDateA());// 当前时间
    	//保存孕妇体重信息,如果id存在则修改,不存在则添加
    	if(StringUtils.isEmpty(gymnasticBarbell.getId())){
    		//判断该天信息是否存在
        	int total = gymnasticBarbellDao.countGymnasticBarbellByUseridAndDate(gymnasticBarbell);
        	if(total>0){
        		throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST,"新增失败,该条数据已存在");
        	}
    		//生成id
        	gymnasticBarbell.setId(SeqUtil.getSeqNo());
        	gymnasticBarbell.setCreateTime(nowTime);
        	gymnasticBarbell.setUpdateTime(nowTime);
        	gymnasticBarbellDao.saveGymnasticBarbell(gymnasticBarbell);
        	gymnasticBarbell.setUpdateType(Constants.HANDLE_TYPE_ADD);
        	gymnasticBarbellDao.saveGymnasticBarbellHis(gymnasticBarbell);
    	}else{
    		gymnasticBarbell.setUpdateTime(nowTime);
    		gymnasticBarbellDao.updateGymnasticBarbell(gymnasticBarbell);
    		//保存历史
    		gymnasticBarbell.setUpdateType(Constants.HANDLE_TYPE_CHANGE);
    		gymnasticBarbellDao.saveGymnasticBarbellHis(gymnasticBarbell);
    	}
    	//步数
    	//查询当天是否存在小米手环上传的数据
    	Map<String,Object> stepmap = Collections.synchronizedMap(new HashMap<String,Object>());
    	stepmap.put("userId", gymnasticBarbell.getUserId());
    	stepmap.put("tenantId", tenantId);
    	stepmap.put("testDate", gymnasticBarbell.getTestDate());
    	List<Map<String,Object>> steplist = activityHuamiDao.getStepForDate(stepmap);
    	if(CollectionUtils.isEmpty(steplist)){//不存在，插入
    		List<PtActivitiesDaily> list = new ArrayList<PtActivitiesDaily>();
    	 	PtActivitiesDaily activity = new PtActivitiesDaily();
    		activity.setId(SeqUtil.getSeqNo());
    		activity.setCalories(gymnasticBarbell.getCalories());
    		activity.setCreateTime(nowTime);
    		activity.setDistance(gymnasticBarbell.getDistance());
    		activity.setRundistance(0);//跑步距离直接默认为0
    		activity.setSteps(gymnasticBarbell.getStepNum());
    		activity.setTestDate(DateTimeUtil.parseDate(gymnasticBarbell.getTestDate(), DateTimeUtil.yyyy_MM_dd));
    		activity.setTenantId(tenantId);
    		activity.setUserId(gymnasticBarbell.getUserId());
    		activity.setSourceState("1");
    		list.add(activity);
    		activityHuamiDao.savePtActivitiesDaily(list);
    		//保存历史
    		activity.setUpdateType(Constants.HANDLE_TYPE_ADD);
    		list.clear();
    		list.add(activity);
    		activityHuamiDao.savePtActivitiesDailyHis(list);
    	}else{//存在
    		if(steplist.get(0).get("sourceState").equals("1")){//修改
    			PtActivitiesDaily activity = new PtActivitiesDaily();
    			activity.setId((String)steplist.get(0).get("ID"));
    			activity.setSteps(gymnasticBarbell.getStepNum());
    			activity.setDistance(gymnasticBarbell.getDistance());
        		activity.setRundistance(0);//跑步距离直接默认为0
        		activity.setCalories(gymnasticBarbell.getCalories());
        		activity.setTestDate(DateTimeUtil.parseDate(gymnasticBarbell.getTestDate(), DateTimeUtil.yyyy_MM_dd));
        		activityHuamiDao.updateActivitiesDaily(activity);
        		activity.setCreateTime(nowTime);
        		activity.setTenantId(tenantId);
        		activity.setUserId(gymnasticBarbell.getUserId());
        		activity.setSourceState("1");
        		activity.setUpdateType(Constants.HANDLE_TYPE_CHANGE);
        		List<PtActivitiesDaily> list = new ArrayList<PtActivitiesDaily>();
        		list.add(activity);
        		activityHuamiDao.savePtActivitiesDailyHis(list);
    		}
    		
    	}
    	rspMap.put("id", gymnasticBarbell.getId());
		return rspMap;
	}
    /**
     * 通过条件查询数据
     * @param weight
     * @return
     */
    @Override
	public Map<String, Object> listWeightByIdAndDate(PtGymnasticBarbell gymnasticBarbell) {
		//创建线程安全的hashmap返回对象
    	Map<String,Object> rspMap = Collections.synchronizedMap(new HashMap<String,Object>());
    	//判断该用户是否存在
    	String tenantId = weightDao.getUserTenantIdByUserId(gymnasticBarbell.getUserId());
    	if(StringUtils.isEmpty(tenantId) && StringUtils.isEmpty(gymnasticBarbell.getId())){
    		throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST,"患者信息不存在");
    	}
    	List<PtGymnasticBarbell> list = gymnasticBarbellDao.listGymnasticBarbell(gymnasticBarbell);
    	if(CollectionUtils.isEmpty(list)){
    		rspMap.put("isBack", false);
    		rspMap.put("PtGymnasticBarbell", new PtGymnasticBarbell());
     	}else{
     		list.get(0).setCreateTime(DateUtil.getTimeStampSec(list.get(0).getCreateTime()));
     		list.get(0).setUpdateTime(DateUtil.getTimeStampSec(list.get(0).getUpdateTime()));
     		
     		rspMap.put("PtGymnasticBarbell", list.get(0));
     		rspMap.put("isBack", true);
     	}
		return rspMap;
	}
    /**
	 * 分页查询
	 */
	@Override
	public Map<String, Object> listGymnasticBarbellForPage(PtGymnasticBarbell gymnasticBarbell) {
		//创建线程安全的hashmap返回对象
    	Map<String,Object> rspMap = Collections.synchronizedMap(new HashMap<String,Object>());
    	//判断该用户是否存在
    	String tenantId = weightDao.getUserTenantIdByUserId(gymnasticBarbell.getUserId());
    	if(StringUtils.isEmpty(tenantId)){
    		throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST,"患者信息不存在");
    	}
    	//体重分页数据
    	List<PtGymnasticBarbell> list = gymnasticBarbellDao.listGymnasticBarbellForPage(gymnasticBarbell);
    	//统计数据总量
    	int totalCount = gymnasticBarbellDao.countGymnasticBarbellForPage(gymnasticBarbell);
    	//处理mysql的timestemp格式问题
    	if(!CollectionUtils.isEmpty(list)){
    		for (int i = 0; i < list.size(); i++) {
    			list.get(i).setCreateTime(DateUtil.getTimeStampSec(list.get(i).getCreateTime()));
    			list.get(i).setUpdateTime(DateUtil.getTimeStampSec(list.get(i).getUpdateTime()));
    		}
    	}
    	rspMap.put("list", list);
    	rspMap.put("totalCount", totalCount);
		return rspMap;
	}
	/**
	 * 条件查询所有
	 */
	@Override
	public Map<String, Object> listGymnasticBarbell(PtGymnasticBarbell gymnasticBarbell) {
		//创建线程安全的hashmap返回对象
    	Map<String,Object> rspMap = Collections.synchronizedMap(new HashMap<String,Object>());
    	//判断该用户是否存在
    	String tenantId = weightDao.getUserTenantIdByUserId(gymnasticBarbell.getUserId());
    	if(StringUtils.isEmpty(tenantId)){
    		throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST,"患者信息不存在");
    	}
    	//体重分页数据
    	List<PtGymnasticBarbell> list = gymnasticBarbellDao.listGymnasticBarbell(gymnasticBarbell);
    	//处理mysql的timestemp格式问题
    	if(!CollectionUtils.isEmpty(list)){
    		for (int i = 0; i < list.size(); i++) {
    			list.get(i).setCreateTime(DateUtil.getTimeStampSec(list.get(i).getCreateTime()));
    			list.get(i).setUpdateTime(DateUtil.getTimeStampSec(list.get(i).getUpdateTime()));
    		}
    	}
    	rspMap.put("list", list);
		return rspMap;
	}
	/**
	 * 删除
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@Override
 	public Map<String, Object> delGymnasticBarbellById(String id) throws Exception {
     	//创建线程安全的hashmap返回对象
     	Map<String,Object> rspMap = Collections.synchronizedMap(new HashMap<String,Object>());
     	//查询用户体重信息
     	PtGymnasticBarbell gymnasticBarbell = new PtGymnasticBarbell();
     	gymnasticBarbell.setId(id);
     	List<PtGymnasticBarbell> list = gymnasticBarbellDao.listGymnasticBarbell(gymnasticBarbell);
     	if(CollectionUtils.isEmpty(list)){
     		throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST,"该条数据已删除,请勿重复操作");
     	}
     	gymnasticBarbell = list.get(0);
     	//删除体重信息
     	gymnasticBarbellDao.deleteById(id);
     	//保存删除记录
     	gymnasticBarbell.setUpdateTime(DateUtil.getTimeString(DateUtil.getSysDateA()));
     	gymnasticBarbell.setUpdateType(Constants.HANDLE_TYPE_DELETE);
     	gymnasticBarbellDao.saveGymnasticBarbellHis(gymnasticBarbell);
 		return rspMap;
 	}
    
}
